<template>
  <div>
    <el-card>
      <!-- 打印区域 -->
      <div ref="print" class="print">
        <div :ref="item" :style="labelStyle" :class="{bgStyle: labelStyle.subline}" v-for="item in labelStyle.num" :key="item">
          <div v-for="item in labelStyle.itemStyle" :key="item.id">
            <div v-if="item.type === 'text'" @mousedown="elMove($event,item)" :style="item">{{ item.text }}</div>
            <img v-if="item.type === 'qrcode'" @mousedown.prevent="elMove($event,item)" :src="item.text" :style="item">
            <img v-if="item.type === 'img'" @mousedown.prevent="elMove($event,item)" :src="item.text" :style="item">
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>

export default {
  name: 'Print',
  props: {
    labelStyle: {
      type: Object,
      required: true,
      default: {}
    }
  },
  data () {
    return {
      // 标签位置
      containerLeft: undefined,
      containerTop: undefined
    }
  },
  mounted () {
    // 获取打印区域在页面中的位置
    // for 循环中的 ref 获取的是数组
    this.containerLeft = this.$refs[1][0].offsetLeft
    this.containerTop = this.$refs[1][0].offsetTop

    this.$bus.$on('print', this.print)
  },
  methods: {
    // 打印
    print () {
      this.$emit('convertLocationMethod')
      this.$nextTick(() => {
        const newStr = this.$refs.print.innerHTML
        const oldStr = document.body.innerHTML
        document.body.innerHTML = newStr
        window.print()
        document.body.innerHTML = oldStr
      })
    },
    elMove (event, item) {
      //计算鼠标在元素上的位置
      const eleLeft = event.offsetX
      const eleTop = event.offsetY

      document.onmousemove = (event) => {
        const left = event.clientX - eleLeft
        const top = event.clientY - eleTop
        item.left = left + 'px'
        item.top = top + 'px'
      }
      document.onmouseup = (event) => {
        document.onmousemove = null

        item.saveLeft = parseInt(item.left) - this.containerLeft
        item.saveTop = parseInt(item.top) - this.containerTop
      }
    }
  }
}
</script>

<style scoped>
.print {
  display: flex;
  flex-wrap: wrap;
}
.bgStyle {
  background: url('~@/assets/bg.png');
}
</style>